package org.lex.notepad.util;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Locale;

import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;

public class CharsetUtils {
	private static String[] DEFAULT_ENCODINGS = { "US-ASCII", "UTF-8", "UTF-16" };
	private static String[] CHINESE_ENCODINGS = { "GB2312", "GBK", "GB18030", "BIG5", "US-ASCII", "UTF-8", "UTF-16" };
	// ==============================================
	private static Charset[] DEFAULT_CHARSETS = null;
	private static Charset[] CHINESE_CHARSETS = null;

	public static String parseFileFormat(Document doc) {
		Object eol = doc.getProperty(DefaultEditorKit.EndOfLineStringProperty);
		if (null == eol)
			return "Unkown";
		return parseOSFromLineSeperator(String.valueOf(eol.toString()));
	}

	public static String parseOSFromLineSeperator(String sep) {
		if (null == sep || 0 == sep.length())
			return "Unkown";
		if (sep.equals("\n"))
			return "UNIX";
		else if (sep.equals("\r"))
			return "Mac";
		else if (sep.equals("\r\n"))
			return "Windows";
		return "Unkown";
	}

	public static Charset[] getCharsets(Locale locale) {
		// chinese locale
		if (locale.equals(Locale.CHINA) || locale.equals(Locale.PRC) || locale.equals(Locale.TAIWAN) || locale.equals(Locale.CHINESE)
				|| locale.equals(Locale.SIMPLIFIED_CHINESE) || locale.equals(Locale.TRADITIONAL_CHINESE))
			return getChineseCharsets();
		else
			// other locales
			return getDefaultCharsets();
	}

	// ========================================================
	private static synchronized Charset[] getChineseCharsets() {
		if (null == CHINESE_CHARSETS) {
			CHINESE_CHARSETS = getValidCharsets(CHINESE_ENCODINGS);
		}
		return CHINESE_CHARSETS;
	}

	private static synchronized Charset[] getDefaultCharsets() {
		if (null == DEFAULT_CHARSETS) {
			DEFAULT_CHARSETS = getValidCharsets(DEFAULT_ENCODINGS);
		}
		return DEFAULT_CHARSETS;
	}

	private static synchronized Charset[] getValidCharsets(String[] names) {
		ArrayList<Charset> list = new ArrayList<Charset>(names.length);
		for (String cn : names) {
			try {
				Charset cs = Charset.forName(cn);
				list.add(cs);
			} catch (Exception e) {
			}
		}
		return list.toArray(new Charset[0]);
	}
}
